<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\model;

use app\api\service\Token;
use app\lib\exception\CurdException;
use app\lib\exception\DrivingLicenseException;
use app\lib\exception\SuccessMessage;
use think\Db;
use think\Exception;
use traits\model\SoftDelete;

/**
 * 行驶证
 * Class DrivingLicense
 * @package app\api\model
 */
class DrivingLicense extends BaseModel
{
    use SoftDelete;

    protected $autoWriteTimestamp = true; // 自动写入时间戳
    protected $deleteTime = 'delete_time';

    /**
     * @Desc 格式化注册日期
     *
     * @param $value
     *
     * @return false|string
     */
    protected function setLicenseRegisterDateAttr($value)
    {
        return strtotime($value);
    }

    /**
     * @Desc 格式化注册日期
     *
     * @param $value
     *
     * @return false|string
     */
    protected function getLicenseRegisterDateAttr($value)
    {
        return date('Ymd', $value);
    }

    /**
     * @Desc 获取用户手机号
     *
     * @param $value
     * @param $data
     *
     * @return bool|float|mixed|string|null
     */
    protected function getColorAttr($value, $data)
    {
        $color = '';
        switch ($data['license_color']) {
            case '蓝':
                $color = '蓝底白字';
                break;
            case '黄':
                $color = '黄底黑字';
                break;
            case '绿':
                $color = '绿底黑字';
                break;
            case '白':
                $color = '白底黑字';
                break;
            case '黑':
                $color = '黑底白字';
                break;
        }
        return $color;
    }

    /**
     * @Desc 获取行驶证列表
     *
     * @param $license_number
     *
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public static function getList($license_number)
    {
        $field = 'id, license_number';
        $where['user_weixin_id'] = Token::getUidFromCache();
        $where['create_time'] = ['>', strtotime('2020-09-24')];
        if (null !== $license_number) {
            $where['license_number'] = ['like', "%{$license_number}%"];
        }
        return (new self)->field($field)->where($where)->select();
    }

    /**
     * @Desc 获取行驶证详情
     *
     * @param $id
     *
     * @return array
     */
    public static function getDetail($id)
    {
        $field = 'id, license_number, license_color, license_typename, user_name, user_address, license_nature, vehicle_brand, vehicle_identification, vin, engine_identification, license_register_date, license_grant_date';
        $list = (new self)->field($field)->where('id', '=', $id)->find();
        return $list->append(['color'])->toArray();
    }

    /**
     * @Desc 新增行驶证数据
     *
     * @param array $licenseData 行驶证信息
     *
     * @return array
     */
    public static function insertLicense(array $licenseData)
    {
        Db::startTrans();
        try {
            $licenseData['open_id'] = Token::getOpenidFromCache();
            $licenseData['user_weixin_id'] = Token::getUidFromCache();
            $license = (new self)->where('user_weixin_id', '=', $licenseData['user_weixin_id'])->where('create_time', '>', strtotime('2020-09-24'))->where('license_number', '=', $licenseData['license_number'])->find();
            if ($license) {
                throw new DrivingLicenseException();
            }
            if (!empty($licenseData['license_image'])) {
                $image_id = Image::insertImage($licenseData['license_image']);
                $licenseData['image_id'] = $image_id;
            }
            unset($licenseData['license_image']);
            $result = self::create($licenseData);
            if (!$result) {
                throw new CurdException();
            }
            Db::commit();
            return [
                'id'             => $result->id,
                'license_number' => $licenseData['license_number'],
            ];
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * @Desc 更新行驶证信息
     *
     * @param $licenseData
     *
     * @return SuccessMessage
     */
    public static function updateLicense($licenseData)
    {
        Db::startTrans();
        try {
            $user_weixin_id = Token::getUidFromCache();
            $license = self::get($licenseData['id']);
            if (!$license) {
                throw new DrivingLicenseException([
                    'code'      => 404,
                    'message'   => '行驶证不存在，请重新操作',
                    'errorCode' => 70001,
                ]);
            }
            $allLicense = (new self)->where('user_weixin_id', '=', $user_weixin_id)->where('id', '<>', $licenseData['id'])->where('create_time', '>', strtotime('2020-09-24'))->column('license_number');
            if (in_array($licenseData['license_number'], $allLicense)) {
                throw new DrivingLicenseException();
            }
            if (!empty($licenseData['license_image'])) {
                if (!empty($license->image_id)) {
                    $imageData = [
                        'id'  => $license->image_id,
                        'url' => $licenseData['license_image'],
                    ];
                    Image::updateImage($imageData);
                } else {
                    $image_id = Image::insertImage($licenseData['license_image']);
                    $licenseData['image_id'] = $image_id;
                }
            }
            unset($licenseData['version'], $licenseData['license_image']);
            if (!self::update($licenseData)) {
                throw new CurdException();
            }
            Db::commit();
            return new SuccessMessage();
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * @Desc 更新行驶证信息(从下单页)
     *
     * @param $license
     *
     * @return array
     */
    public static function updateLicenseFromOrder($license)
    {
        if (!self::update($license)) {
            throw new CurdException();
        }
        $data = self::get($license['id']);
        return [
            'user_name'      => $data->getAttr('user_name'),
            'license_number' => $data->getAttr('license_number'),
        ];
    }

    /**
     * @Desc 删除行驶证
     *
     * @param $id
     *
     * @return SuccessMessage
     */
    public static function deleteLicense($id)
    {
        if (!self::destroy($id)) {
            throw new CurdException([
                'message'   => '删除失败，请稍后再试',
                'errorCode' => 60003,
            ]);
        }
        return new SuccessMessage();
    }
}